<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" :title="title" @ok="handleSubmit" 
    width="700px" 
    :defaultFullscreen="true"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { inputFormSchemas } from './data';
import { saveOrUpdateAgreement } from './api';
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage()
// 声明Emits
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: '15%',
  schemas: inputFormSchemas,
  showActionButtonGroup: false,
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
});
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    await setFieldsValue({
      ...data.record,
    });
  }
});

const title = computed(() => (!unref(isUpdate) ? '新增协议' : '编辑协议'));

async function handleSubmit(v) {
  try {
    let values = await validate();
    setModalProps({ confirmLoading: true });
    await saveOrUpdateAgreement(values, isUpdate.value);
    closeModal();
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
